package graphics;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;

import controller.Constants;

/**
 * Text
 * 
 * @author Jie Zhao(288654)
 * 
 */
public class Text extends RectBoundedShape {
	private String text = "";

	public Text() {
	}
	@Override
	public String toString() {
		StringBuffer sb = new StringBuffer();
		sb.append("text:");
		sb.append(getLineColor().getRGB()+":");
		sb.append((isFilled()?"1":"0") + ":");
		sb.append(getFilledColor().getRGB()+":");
		sb.append(getStroke().getLineWidth()+":");
		sb.append(getStartPoint().x+","+getStartPoint().y+":");
		sb.append(getEndPoint().x+","+getEndPoint().y+":");
		if(!text.equals(""))sb.append(text.replaceAll(":", "~~"));
		return sb.toString();
	}

	@Override
	public void fromString(String str) {
		try{
		String[] data = str.split(":");
		if(!data[0].equals("text"))return;
		setLineColor(new Color(Integer.parseInt(data[1])));
		setFilled(data[2].equals("1"));
		setFilledColor(new Color(Integer.parseInt(data[3])));
		setStroke(new BasicStroke(Float.parseFloat(data[4]),BasicStroke.CAP_ROUND,BasicStroke.CAP_ROUND));
		String[] point = data[5].split(",");
		setStartPoint(new Point(Integer.parseInt(point[0]),Integer.parseInt(point[1])));
		point = data[6].split(",");
		setEndPoint(new Point(Integer.parseInt(point[0]),Integer.parseInt(point[1])));
		if(data.length == 8)setText(data[7].replaceAll("~~", ":"));
		}catch(Exception e)
		{
			if(Constants.DEBUG)e.printStackTrace();
		}
	}
	@Override
	/**
	 * draw the text
	 */
	public void draw(Graphics g) {
		calculateBoundedRect();
		super.draw(g);
		Graphics2D g2d = (Graphics2D)g;
		g2d.setColor(getLineColor());
		Font oldFont = g2d.getFont();
		Font f = new Font(Font.DIALOG,Font.PLAIN,(int)(10+getStroke().getLineWidth()));
		g2d.setFont(f);
		g2d.drawString(text, startPoint.x, startPoint.y);
		g2d.setFont(oldFont);
	}


	public void setText(String text)
	{
		this.text = text;
	}
	
	public String getText()
	{
		return text;
	}
	public static void main(String[] args) {
		Text c = new Text();
		c.setStartPoint(new Point(12,34));
		c.setEndPoint(new Point(56,78));
		c.setText("Hello :World");
		System.out.println(c);
		
		Text c2 = new Text();
		c2.fromString(c.toString());
		System.out.println(c2.getText());
	}
}
